const runWithBrowser = require('./doWithBrowser')
const runWithInterface = require('./doWithInterface')
const cmdArgs = require('./getEnv')
const schedule = require('node-schedule')
const Log = require('./log')
const logger = new Log()
function generateRunner() {
    let index = 0
    const max = 10
    return async function run(config) {
        if (index < max) {
            try {
                logger.error(`尝试第${index + 1}次`)
                logger.info(JSON.stringify(cmdArgs))
                if (cmdArgs.browser) {
                    await runWithBrowser(config)
                } else {
                    await runWithInterface(config)
                }
            } catch(e) {
                console.log(e.message)
                index += 1
                await run(config)
            }
        } else {
            logger.error('尝试失败10次')
        }
    }
}


var rule = new schedule.RecurrenceRule();
rule.hour = 6;
rule.minute = 15;
// rule.second=[new schedule.Range(0, 59)]
schedule.scheduleJob(rule, async function () {
    const configs = require('./config')
    for (let config of configs) {
        const run = generateRunner()
        await run(config)
    }
});

if (cmdArgs.dev || cmdArgs.autoStart) {
    // autoStart()
    (async () => {
        const configs = require('./config')
        for (let config of configs) {
            const run = generateRunner()
            await run(config)
        }
    })()
}
